# coding=utf-8
from datetime import datetime

from flask import jsonify

from blues.cloud import bp
from blues.cloud.base import request_asapi
from database2 import db_exec_many


def record_slb() -> bool:
    # 获取ASAPI接口数据
    asapi_data = request_asapi(1, "Slb", "2014-05-15", "DescribeLoadBalancers")
    if not asapi_data:
        return False
    # 准备批量插入数据库，先初始化一个空数组，在循环中不断追加
    values_list = []
    for i in asapi_data['LoadBalancers']['LoadBalancer']:
        tmp_tuple = (
            i['LoadBalancerId'], i['Address'], i['LoadBalancerName'], i['ResourceGroup'], i['ResourceGroupName'],
            i['NetworkType'], i['VpcId'], i['VSwitchId'], i['AddressIPVersion'], i['LoadBalancerSpec'], i['Department'],
            i['DepartmentName'], i['AddressType'], i['LoadBalancerStatus'], i['CreateTime'], datetime.now())
        values_list.append(tmp_tuple)
    table = 'c_slb_info'
    fields = "lb_id,address,lb_name,resource_group,resource_group_name,network_type,vpc_id,vswitch_id,address_ip_version," \
             "lb_spec,department,department_name,address_type,status,create_time,record_time"
    # 使用上面的数据，批量插入db
    db_success = db_exec_many(table, fields, values_list)
    if not db_success:
        return False
    return True


@bp.route('/api/v1/cloud/record_slb_info', methods=['POST'])
def record_slb_api():
    success = record_slb()
    if not success:
        return jsonify({'code': 500})
    return jsonify({'code': 200})
